package cn.cnsy123.blog.application.controller;

import cn.cnsy123.blog.application.http.base.BaseResponse;
import cn.cnsy123.blog.application.http.request.UserLoginRequest;
import cn.cnsy123.blog.application.http.response.UserLoginResponse;
import cn.cnsy123.blog.application.http.response.UserRegisterResponse;
import cn.cnsy123.blog.application.service.UserInfoService;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;

@RestController
public class UserLoginController {

    private static final Logger logger = LoggerFactory.getLogger(UserLoginController.class);

    @Autowired
    private UserInfoService userInfoService;


    @PostMapping(value = "/login")
    public BaseResponse<UserLoginResponse> userLogin(@Valid @RequestBody UserLoginRequest request, BindingResult result){
        logger.info("用户登录-请求参数:{}", JSON.toJSONString(request));
        BaseResponse<UserLoginResponse> response = new BaseResponse<UserLoginResponse>();
        response.setCode("0000");
        response.setMessage("系统请求成功");
        response.setRequestTime(new Date(System.currentTimeMillis()));
        if(result.hasErrors()){
            response.setData(new UserLoginResponse("1003",result.getAllErrors().get(0).getDefaultMessage()));
        }else{
            UserLoginResponse userLoginResponse = null;
            try {
                userLoginResponse = userInfoService.loginCore(request);
            }catch(Exception e){
                logger.error("登录用户失败",e);
                userLoginResponse = new UserLoginResponse("1099","系统登录失败，服务异常，请稍后重试");
            }
            response.setData(userLoginResponse);
        }

        response.setResponseTime(new Date(System.currentTimeMillis()));
        logger.info("用户登录-返回参数:{}", JSON.toJSONString(response));
        return response;
    }
}
